<template>
  <div>
    <n-button @click="showNewModal = true"><template #icon>
        <n-icon> <i class="bi bi-plus-circle"></i></n-icon>
      </template>{{ $t("developer.center.new") }}</n-button>&nbsp;
    <n-button @click="this.$router.go()"><template #icon>
        <n-icon> <i class="bi bi-arrow-clockwise"></i></n-icon>
      </template>{{ $t("developer.center.reload") }}</n-button>

    <div class="pt-2">
      <div class="pt-2">
        <n-data-table :columns="clientsColumns" :data="clients" :pagination="{ pageSize: 10 }" />
      </div>

      <n-modal v-model:show="showNewModal">
        <n-card style="width: 600px" :title="$t('developer.center.new-client.title')" :bordered="false" size="huge"
          role="dialog" aria-modal="true">
          <n-form ref="newForm" :model="newModel" :rules="newRules">
            <n-form-item :label="$t('developer.center.new-client.client-name')" path="clientName">
              <n-input v-model:value="newModel.clientName" @keydown.enter.prevent />
            </n-form-item>
            <n-form-item :label="$t('developer.center.new-client.scope')" path="scope">
              <n-input v-model:value="newModel.scope" :placeholder="
                $t('developer.center.new-client.placeholders.scope')
              " @keydown.enter.prevent />
            </n-form-item>
            <n-form-item :label="$t('developer.center.new-client.avatar')" path="avatar">
              <n-input v-model:value="newModel.avatar" :placeholder="
                $t('developer.center.new-client.placeholders.avatar')
              " @keydown.enter.prevent />
            </n-form-item>
            <n-button :loading="pushing" style="width: 100%" type="primary" @click="createClient">
              {{ $t("common.actions.create") }}
            </n-button>
          </n-form>
        </n-card>
      </n-modal>
    </div>   </div>
</template>

<script setup>
import axiosHttp from "axios";
import Loading from "vue-element-loading";
import { useCookies } from "vue3-cookies";
import {
  NDataTable,
  NTag,
  NModal,
  NCard,
  NForm,
  NInput,
  NFormItem,
  NButton,
  NIcon,
  NStatistic,
  NNumberAnimation,
  useMessage,
} from "naive-ui";
import { ref, reactive, h, defineEmits, defineProps } from "vue";
import { copyText } from "vue3-clipboard";
import { useStore } from "../../../stores/main";
import { useI18n } from "vue-i18n";

const { cookies } = useCookies();
const axios = axiosHttp.create({ validateStatus: () => true });
const message = useMessage();

const { t } = useI18n();
const store = useStore();

const showNewModal = ref(false);
const newForm = ref(null);
const newModel = reactive({
  clientName: "",
  scope: "",
  avatar: "",
  response: {
    display: false,
    clientId: "",
    clientSecret: "",
  },
});
const newRules = {
  clientName: [
    {
      required: true,
      message: t("developer.center.new-client.validate.client-name"),
    },
  ],
  scope: [
    {
      required: true,
      message: t("developer.center.new-client.validate.scope"),
    },
  ],
  avatar: [
    {
      required: true,
      message: t("developer.center.new-client.validate.avatar"),
    },
    {
      validator: (rule, value) => {
        if (
          !new RegExp(
            /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/
          ).test(value)
        ) {
          return new Error(
            t("developer.center.new-client.validate.avatar-invalid")
          );
        }
      },
    },
  ],
};

const pushing = ref(false);
const pulling = ref(false);
const emit = defineEmits(["reload", "created"]);
const { clients } = defineProps({ clients: Array });

const clientsColumns = [
  {
    title: t("developer.center.client.avatar"),
    key: "avatar",
    render(row) {
      return h("img", {
        width: 32,
        height: 32,
        class: "rounded-3",
        src: row.avatar,
      });
    },
  },
  { title: t("developer.center.client.client-name"), key: "client_name" },
  {
    title: t("developer.center.client.client-id"),
    key: "client_id",
    render(row) {
      return h(
        "code",
        { onClick: () => copy(row.client_id) },
        row.client_id
      );
    },
  },
  {
    title: t("developer.center.client.scope"),
    key: "scope",
    render(row) {
      const tags = row.scope.split(",").map((scopeKey) => {
        return h(
          NTag,
          { style: { marginRight: "6px" }, type: "info" },
          { default: () => scopeKey }
        );
      });
      return tags;
    },
  },
  {
    title: t("developer.center.client.created-at"),
    key: "created_at",
    render(row) {
      return h("span", new Date(row.created_at).toLocaleString());
    },
  },
  {
    title: t("developer.center.client.action"),
    key: "actions",
    render(row) {
      return h(
        NButton,
        {
          onClick: () => deleteClient(row.client_id),
          strong: true,
          size: "small",
          type: "error",
        },
        { default: () => t("common.actions.delete") }
      );
    },
  },
];

function copy(text) {
  copyText(text, undefined, (error) => {
    if (error) {
      message.error(t("common.messages.copy-failed"))
      console.error(error);
    } else {
      message.success(t("common.messages.copy-success"))
    }
  });
}

function createClient() {
  newForm.value.validate((error) => {
    if (!error) {
      pushing.value = true;
      axios
        .put(
          "/api/management/developer/client",
          {
            client_name: newModel.clientName,
            scope: newModel.scope,
            avatar: newModel.avatar,
          },
          {
            headers: { Authorization: "Bearer " + cookies.get("access_token") },
          }
        )
        .catch(() => {
          message.error(t("common.messages.request-unknown-error"));
          pushing.value = false;
        })
        .then((response) => {
          if (response.status === 400) {
            message.warning(t("developer.center.messages.invalid"));
            pushing.value = false;
          } else {
            message.success(t("developer.center.messages.success"));
            const response = {
              clientId: response.data["client"]["client_secret"],
              clientSecret: response.data["client"]["client_secret"],
            }
            showNewModal.value = false;
            pushing.value = false;
            emit("created", response);
            emit("reload");
          }
        });
    }
  });
}

function deleteClient(client_id) {
  if (confirm(t("developer.center.messages.confirm"))) {
    console.log(client_id);
    axios
      .delete("/api/management/developer/client?id=" + client_id, {
        headers: { Authorization: "Bearer " + cookies.get("access_token") },
      })
      .then(() => {
        message.success(
          t("developer.center.messages.deleted.0") +
          client_id.substring(0, 8) +
          t("developer.center.messages.deleted.1")
        );
        emit("reload");
      });
  }
}
</script>

<style>code {
  cursor: copy;
}</style>
